import axios from 'axios'

// @params
//      @url<String>请求url
//      @requestType<String>请求方式
//      @params<Object>参数
//      @contentType<String> 默认'application/x-www-form-urlencoded'
// @result
//      http返回结果

const request = (url, requestType, params, contentType = 'application/x-www-form-urlencoded') => {
  // 处理参数
  let param = {}
  if (requestType === 'get' || requestType === 'GET' || contentType === 'application/x-www-form-urlencoded') {
    const paramsArr = []
    for (const key in params) {
      paramsArr.push(`${key}=${params[key]}`)
    }
    param = paramsArr.join('&')
    // console.log(param)
  } else {
    param = params
  }

  // 请求
  return axios({
    method: requestType,
    url: requestType === 'get' || requestType === 'GET' ? `${url}?${param}` : `${url}`,
    data: param
  }).then(res => [null, res]).catch(err => [err])
}

// axios拦截器

axios.interceptors.response.use((res) => {
  // http请求成功

  if (res.status === 200) {
    return res.data
  }
}, function(err) {
  return Promise.reject(err)
})

export default request
